package simplecert

import (
	"crypto/sha256"
	"errors"
	"fmt"
	"io/ioutil"
	"os"

	"gitee.com/shuohe/go-shlib"
)

func passwordToKey(passwd string) shlib.ISecretKey {
	h := sha256.New()
	h.Write([]byte(passwd))
	d := h.Sum(nil)

	for i := 0; i < 16; i++ {
		d[i] ^= d[i+16]
	}
	k, _, _ := shlib.AesKeyFactory(shlib.KeyType_Secret, d)

	return k.(shlib.ISecretKey)
}

func WriteKeyFile(filename string, key shlib.IKey, password string) error {
	k := passwordToKey(password)

	f, err := os.Create(filename)
	if err != nil {
		return errors.New(fmt.Sprintf("Can not create file '%s'.", filename))
	}

	_, err = f.Write(k.Encrypt(key.Export()))
	if err != nil {
		f.Close()
		os.Remove(filename)
		return errors.New("I/O error.")
	}

	return f.Close()
}

func ReadKeyFile(filename string, password string) (shlib.IKey, error) {
	k := passwordToKey(password)

	b, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("Can not read file '%s'.", filename))
	}

	b, err = k.Decrypt(b)
	if err != nil {
		return nil, errors.New("Key file is corrupted.")
	}

	return shlib.LoadKey(b)
}

func ReadKeyFileNe(filename string, password string) shlib.IKey {
	key, err := ReadKeyFile(filename, password)
	if err != nil {
		panic(err)
	}

	return key
}
